package com.songcha.library_common.ui.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewParent
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.absoluteValue

 class ViewPagerScrollRecyclerView
 @JvmOverloads
 constructor(  context: Context,
               attrs: AttributeSet? = null,
               defStyle: Int = 0)
     : RecyclerView (context,attrs,defStyle){

    var lastX=0f
    var lastY=0f

     fun getAction(ev:MotionEvent):String{
         when(ev.action){
             MotionEvent.ACTION_DOWN->return "ACTION_DOWN"
             MotionEvent.ACTION_MOVE->return "ACTION_MOVE"
             MotionEvent.ACTION_UP->return "ACTION_UP"
             MotionEvent.ACTION_CANCEL->return "ACTION_CANCEL"
         }
         return ""
     }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {

        ev?.let {

            var parent=this.parent
            while (parent !is ViewParent){
                parent=parent.parent
                if(parent==null){
                    throw Throwable("can not find viewpager in recyclerview")
                }
            }

            if(ev.action==MotionEvent.ACTION_DOWN) {
                lastX=ev.x
                lastY=ev.y
            }else if(ev.action==MotionEvent.ACTION_MOVE){
                //如果是竖向滑动则禁止viewpager拦截,否则继续分发
                //if is slide in vertical,prohibit viewpager intercept,otherwise continue dispatch
                if((ev.y-lastY).absoluteValue>=(ev.x-lastX).absoluteValue){
                    parent.requestDisallowInterceptTouchEvent(true)
                    //return true
                }else{
                    parent.requestDisallowInterceptTouchEvent(false)
                    //return false
                }
            }else if(ev.action==MotionEvent.ACTION_UP){
                parent.parent.requestDisallowInterceptTouchEvent(false)
                //return false
            }
        }

        return super.dispatchTouchEvent(ev)

    }




}